package de.betagames.dreamworld.charactereditor.view;

import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class NewCharacterView extends JFrame {

	private JTextField txt;
	private CharacterChooser window;

	public NewCharacterView(CharacterChooser cc) {
		window = cc;
		setTitle("Dreaming new Dream-Ego");
		setSize(320, 150);
		setResizable(false);
		setLocationRelativeTo(null);
		setLayout(new GridLayout(3, 1));
		add(new JLabel("Please enter the name of your Dream-Ego:"));
		txt = new JTextField();
		add(txt);
		add(getButtons());
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setVisible(true);

	}

	private JPanel getButtons() {

		JPanel panel = new JPanel();

		JButton b1 = new JButton("Abort");
		JButton b2 = new JButton("OK");

		b1.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});

		b2.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				save(txt.getText());
			}
		});

		panel.setLayout(new GridLayout(1, 2));

		panel.add(b1);
		panel.add(b2);

		return panel;

	}

	private void save(String name) {

		try {
			File f = new File(System.getProperty("user.dir") + "/Characters/"
					+ name + ".char");
			f.setWritable(true, false);
			if (f.createNewFile()) {
				FileWriter fw = new FileWriter(f);
				fw.append("name=" + name + "\r\n");
				fw.append("str=5" + "\r\n");
				fw.append("dex=5" + "\r\n");
				fw.append("con=5" + "\r\n");
				fw.append("int=5" + "\r\n");
				fw.append("portrait=default");
				fw.flush();
				JOptionPane.showMessageDialog(this,
						"Your Dream-Ego has been dreamt.", "SUCCESS",
						JOptionPane.INFORMATION_MESSAGE);
				window.fillComboBox();
				dispose();
			} else {
				JOptionPane.showMessageDialog(this,
						"<html>You tried hard, but you couldn't sleep.<br>"
								+ "Your Dream-Ego couldn't be dreamed.</html>",
						"FAILURE", JOptionPane.ERROR_MESSAGE);
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(this,
					"<html>You tried hard, but you couldn't sleep.<br>"
							+ "Your Dream-Ego couldn't be dreamed.</html>",
					"FAILURE", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}
	}
}
